﻿using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using FileIO.ViewModels;

namespace PrismTest.Views;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContextChanged += MainWindow_DataContextChanged;
        TryAttachBrowseEvent(this.DataContext);
    }

    private void MainWindow_DataContextChanged(object? sender, DependencyPropertyChangedEventArgs e)
    {
        TryAttachBrowseEvent(e.NewValue);
    }

    private void TryAttachBrowseEvent(object? dataContext)
    {
        if (dataContext is MainWindowViewModel vm)
        {
            vm.BrowseFileRequested -= OnBrowseFileRequested;
            vm.BrowseFileRequested += OnBrowseFileRequested;
        }
    }

    private void OnBrowseFileRequested()
    {
        var dlg = new OpenFileDialog();
        if (dlg.ShowDialog() == true)
        {
            if (DataContext is MainWindowViewModel vm)
                vm.FilePath = dlg.FileName;
        }
    }
}